define(function (require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    require('../../../../core/apps/dashboard/dashCharts');
    var Highcharts = require('../../../../oldcrm/js/core/charts.rk');
    var chartType = {
        salesGoal: 1001, //销售目标完成情况（绩效仪表盘）
        salesFunnel: 1004, //销售漏斗（绩效仪表盘）
        salesRecentFocus: 1002, //近期重点商机（绩效仪表盘）
        salesPK: 1003, //销售业绩PK（绩效仪表盘）
        salesActivity: 1005, //,//活动记录类型（销售行为仪表盘）
        top10Customer: 1006, //,//签约大客户排行Top10（绩效仪表盘）
        top10Opportunity: 1007 //进行中的商机Top10（绩效仪表盘）
    };
    $.widget('rk.dashboardCtrl', {
        _create: function () {
            var me = this;
            var elem = me.element;
        },
        _init: function(){
            var me = this;
            var elem = me.element;

            me._loadData();

            me._bindHandler();
            me._initChartEvent();
        },
        _loadData: function(){
            var me = this;
            var elem = me.element;
            rk.post("/json/crm_dashboard/get-home-chart.action", {viewCase:1}, function(json) {
                if (json.status == 0) {
                    me.data = json.data;
                    require.async(['page/tmpl/index/dashboard/tpl_index_dashboard.tpl'], function(tmpl) {
                        var html = rk.templateText(tmpl, {
                            data: me.data
                        });
                        elem.html(html);
                        me._initPage(me.data);
                    });
                } else if(json.status == 300001) {
                    elem.find('div.js-dashboard_list').hide();
                }
            }).fail(function(def, code, message) {
                def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
            });
        },
        _initPage: function(data){
            var me = this;
            var elem = me.element;
            $.each(data.searchFavorites,function (i,o) {
                me._getChartInfo(o,elem.find('div.js-dashboard_list'));
                me._initChartEvent(elem);
            });
        },
        _bindHandler: function(){
            var me = this;
            var elem = me.element;

            elem.on('click', 'a[act=more]', function() {
                for(var i=me.data.defaultNumber; i<=me.data.total; i++){
                    elem.find("li[act=task_" + i + "]").eq(0).show();
                }
                //隐藏更多
                elem.find("a[act=more]").eq(0).hide();
            });
            //添加仪表盘
            elem.on('click', 'a[act=addDashboard]', function() {
                rk.post("/json/crm_dashboard/get-home-chart.action", {viewCase:2}, function(json) {
                    if (json.status == 0) {
                        require.async(['page/tmpl/index/dashboard/tpl_index_dashboard_add.tpl'], function(tmpl) {
                            rk.dialog({
                                title: rk.i18n('DASH_'),
                                width:540,
                                html: rk.templateText(tmpl, {}),
                                success: function (contentElem, footerElem){
                                    var chartSelect = contentElem.find('select[act=chartSelect]'),chartContent=contentElem.find('div.js-chart_content'),charts=[],selectOpt='';
                                    chartSelect.selectmenu();
                                    $.each(json.data.searchFavorites, function(k, o) {
                                        selectOpt += "<option value='" + o.id + "'>" + o.name + "</option>";
                                        charts[o.id] = o;
                                    });
                                    chartSelect.html(selectOpt);
                                    chartSelect.attr("isload","true");
                                    chartSelect.selectmenu('refresh', true);
                                    chartSelect.selectmenu({
                                        change: function( event, ui ) {
                                            var value = ui.item.value;
                                            chartContent.empty();
                                            me._getChartInfo(charts[value],chartContent);
                                            me._initChartEvent(contentElem);
                                        }
                                    });
                                    chartSelect.attr('selectedIndex', 0);
                                    chartContent.empty();
                                    me._getChartInfo(charts[chartSelect.val()],chartContent);
                                    me._initChartEvent(contentElem);
                                    rk.repositionDialog();
                                    footerElem.on('click', 'a[act=ok]', function() {
                                        var favId = chartSelect.val();
                                        if( favId != null  && favId != '' ) {
                                            $(this).beLoading();
                                            rk.post("/json/crm_dashboard/save-home-chart.action", {favoriteId:favId}, function(json) {
                                                if (json.status == 0) {
                                                    me._getChartInfo(charts[favId],elem.find('div.js-dashboard_list'));
                                                    me._initChartEvent(elem);
                                                    $.msg(rk.i18n('DASH___376'), 1);
                                                    rk.closeDialog();
                                                } else {
                                                    $(this).unLoading();
                                                }
                                            });
                                        } else {
                                            $.msg(rk.i18n('DASH___377'));
                                        }
                                    });
                                    footerElem.on('click', 'a[act=cancel]', function() {
                                        rk.closeDialog();
                                    });
                                },
                                footer: ['cancel', 'ok']//弹框的按钮
                            });
                        });
                    } else if(json.status == 400001 ) {
                        $.msg(rk.i18n('DASH___378'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });
        },
        _formatData: function(data){
            var me = this;
            var elem = me.element;
        },
        _getChartInfo: function(chart,target) {
            var me = this,elem = me.element;
            var content = ['<div chartid="', chart.id, '" class="report_block">',
                '<div class="report_box">',
                '<div class="title"><span class="report_detail" >', $.htmlEncode(chart.name), '</span><a href="javascript:;" class="close js-remove_chart" title="'+rk.i18n('DASH___379')+'" chartid="', chart.id, '"></a></div>',
                '<div class="report_top clear js-chart_top ',chart.type == chartType.salesFunnel ? ' report_top_marlt ':'','">',
                me._getTopInfo(chart),
                '</div> ',
                '<div class="dashboard-loading js_dashboard-loading"><img src="',
                SESSION.resDomain,
                '/static/img/v3.0/dashboard_loading.png" alt=""><div class="loading-text">'+rk.i18n('DASH___380')+'</div></div>',
                '<div chart="', chart.id, '" type="',chart.type,'" class="cont_wrap">','</div>',
                '<div class="chart_des js-chart_des"></div>',
                '</div>',
                '</div>'
            ].join('');
            $(content).appendTo(target);
            me._draw(target.find(['div[chart=', chart.id, ']'].join('')), chart);

            $.each(target.find('div.meter_edit'), function(i, o) {
                var $input = $(o).find('input'),
                    $start = $($input[0]),
                    $end = $($input[1]);
                $start.datepicker({
                    changeMonth: true,
                    changeYear: true,
                    onClose: function(selectedDate) {
                        $end.datepicker("option", "minDate", selectedDate);
                    }
                });
                $end.datepicker({
                    changeMonth: true,
                    changeYear: true,
                    onClose: function(selectedDate) {
                        $start.datepicker("option", "maxDate", selectedDate);
                    }
                });
            });
        },
        _initChartEvent:function( elem ) {
            var me = this,elem =$(elem);
            // 图表的时间filter,包括自定义区间的切换
            elem.off('change.dashboardCtrl', 'div.meter_edit select.js-date_type').on('change.dashboardCtrl', 'div.meter_edit select.js-date_type', function(evt) {
                if ($(this).val() == 1) {
                    $('.js-date_value').empty();
                    $('.js-date_value').append('<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option>');
                } else {
                    $('.js-date_value').empty();
                    $('.js-date_value').append('<option value="1">1</option><option value="2">2</option>');
                }
            });
            elem.off('click.dashboardCtrl', 'div.report_top .js-chart-filter').on('click.dashboardCtrl', 'div.report_top .js-chart-filter', function(evt) {
                var period = $(this).attr('period');
                var $parent = $(this).parents('div.report_top');
                if (period == 'custom') {
                    $(this).next().toggle();
                } else {
                    $parent.find('.js-chart-filter').removeClass('tabon');
                    $(this).addClass('tabon');
                    $parent.find('div.meter_edit').hide();
                    var $chart = $parent.next().next();
                    var chartId = $chart.attr('chart');
                    var type = $chart.attr('type');
                    var data = {
                        chartId: chartId,
                        favoriteId: chartId,
                        'periodType': $(this).attr('period')
                    };
                    // 活动记录排行,有个拜访记录类型,特殊处理
                    var box = $(this).parents('div.report_box');
                    if (box.has('div.rank_bot').length) {
                        data = {
                            chartId: chartId,
                            favoriteId: chartId,
                            periodType: period,
                            recordType: box.find('div.rank_bot').find('a.green_button').attr('tag')
                        };
                    }
                    me._reload($chart, {id:chartId,type:type}, data);
                }
            });
            elem.off('click.dashboardCtrl', 'div.meter_edit a.green_button').on('click.dashboardCtrl', 'div.meter_edit a.green_button', function(evt) {
                var $lnk = $(this);
                var $div = $lnk.parents('div.meter_edit');
                var $type = $lnk.attr("type");
                var box = $(this).parents('div.report_box');
                var $chart = box.find('div.cont_wrap');
                var chartId = $chart.attr('chart');
                if ($type == chartType.salesRecentFocus) {
                    var $num = $div.find('select').first().val();
                    var $dateType = $div.find('select').last().val();
                    box.find('span.js-recent_num').html($num);
                    box.find('span.js-recent_type').html($div.find('select').last().find('option:selected').text());
                    $div.hide();
                    // 活动记录排行,有个拜访记录类型,特殊处理
                    var postData = {
                        chartId: chartId,
                        favoriteId: chartId,
                        dateNum: $num,
                        periodType: $dateType == '1' ? 'week' : 'month'
                    };
                    if (box.has('div.rank_bot').length) {
                        postData.recordType = box.find('div.rank_bot').find('a.green_button').attr('tag');
                    }
                    me._reload($chart, {id:chartId,type:$type}, postData);
                } else {
                    var start = $.trim($div.find('input.js-start-date').val());
                    var end = $.trim($div.find('input.js-end-date').val());
                    if (start == '') {
                        $.msg(rk.i18n('DASH___381'));
                        return;
                    }
                    if (end == '') {
                        $.msg(rk.i18n('DASH___382'));
                        return;
                    }
                    $div.hide();
                    // 活动记录排行,有个拜访记录类型,特殊处理
                    var postData = {
                        chartId: chartId,
                        favoriteId: chartId,
                        startTime: new Date(start).getTime(),
                        endTime: new Date(end).getTime()
                    };
                    if (box.has('div.rank_bot').length) {
                        postData.recordType = box.find('div.rank_bot').find('a.green_button').attr('tag');
                    }
                    box.find('.js-chart-filter').removeClass('tabon');
                    $div.parent().find('.js-chart-filter').addClass('tabon');
                    me._reload($chart, {id:chartId,type:$type}, postData);
                }
                return false;
            });

            elem.off('click.dashboardCtrl', 'a.js-remove_chart').on('click.dashboardCtrl', 'a.js-remove_chart', function(evt) {
                var $lnk = $(this),favId=$lnk.attr("chartId");
                rk.confirm( rk.i18n('DASH___383'),{okText: rk.i18n('DASH___384')}, function (){
                        rk.post("/json/crm_dashboard/remove-home-chart.action", {favoriteId:favId}, function(json) {
                            if (json.status == 0) {
                                $.msg(rk.i18n('DASH___385'),1);
                                elem.find(['div[chartid=', favId, ']'].join('')).remove();
                            }
                        }).fail(function(def, code, message) {
                            def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                        });
                    },function (){
                    }
                );
            });
            elem.find('a.js-remove_chart').beTip({dir:'left'});
        },
        _reload: function(container, chart, param) {
            var me = this,elem = me.element;
            me._reloadFun(container, chart, param);
        },
        _draw: function(container, chart) {
            var me = this,elem = me.element;
            $.postJson('/json/crm_dashboard/get-chart.action', {
                favoriteId: chart.id,
                dashBoardType :chart.type
            }).done(function(json) {
                if (json.status == 0) {
                    me._drawFun(container, json.data);
                    container.parents(['div[chartid=', chart.id, ']'].join('')).find('div.js_dashboard-loading').hide();
                } else {
                    $.msg(rk.i18n('DASH___386'));
                    container.parents(['div[chartid=', chart.id, ']'].join('')).find('div.js_dashboard-loading').hide();
                }
            }).fail(function(def, code, message) {
                container.parents(['div[chartid=', chart.id, ']'].join('')).find('div.js_dashboard-loading').hide();
            });
        },
        _reloadFun:function (container, chart, param) {
            if (!chart.type) {
                return;
            }
            switch (parseInt(chart.type)) {
                case chartType.salesGoal:
                    container.salesGoal('reload', param);
                    break;
                case chartType.salesRecentFocus:
                    container.salesRecentFocus('reload', param);
                    break;
                case chartType.salesPK:
                    container.salesPK('reload', param);
                    break;
                case chartType.salesFunnel:
                    container.salesFunnel('reload', param);
                    break;
                case chartType.salesActivity:
                    container.salesActivity('reload', param);
                    break;
                case chartType.top10Customer:
                    container.top10Customer('reload', param);
                    break;
                case chartType.top10Opportunity:
                    container.top10Opportunity('reload', param);
                    break;
            }
        },
        _drawFun:function (container, chart) {
            switch (parseInt(chart.type)) {
                case chartType.salesGoal:
                    container.salesGoal({
                        chart: chart
                    });
                    break;
                case chartType.salesRecentFocus:
                    container.salesRecentFocus({
                        chart: chart
                    });
                    break;
                case chartType.salesPK:
                    container.salesPK({
                        chart: chart
                    });
                    break;
                case chartType.salesFunnel:
                    container.salesFunnel({
                        chart: chart
                    });
                    break;
                case chartType.salesActivity:
                    container.salesActivity({
                        chart: chart
                    });
                    break;
                case chartType.top10Customer:
                    container.top10Customer({
                        chart: chart
                    });
                    break;
                case chartType.top10Opportunity:
                    container.top10Opportunity({
                        chart: chart
                    });
                    break;
            }
        },
        _getTopInfo:function (o) {
            var $result;
            var $calendarInfo = ['<div class="calendar_tag_area">',
                '<a period="custom" class="calendar_tag js-chart-filter">'+rk.i18n('DASH___390')+'<em>|</em></a>',
                '<div class="meter_edit">',
                '<div class="calendar_tag_box clear"><em>'+rk.i18n('DASH___387')+'：</em><input type="text" placeholder="'+rk.i18n('DASH___388')+'" class="text js-start-date " ><b>'+rk.i18n('CRM_CORE_TO')+'</b><input type="text" placeholder="'+rk.i18n('DASH___389')+'" class="text js-end-date "></div>',
                '<a title="" class="green_button" href="javascript:;" type="', chartType.salesFunnel, '">'+rk.i18n('CRM_CORE_CONFIRM')+'</a>',
                '</div>',
                '</div>'
            ].join('');
            var $rescentFocusInfo = ['<div class="calendar_tag_area">',
                '<a period="custom" class="calendar_tag js-chart-filter">'+rk.i18n('DASH___390')+'<em>|</em></a>',
                '<div class="meter_edit">',
                '<div class="calendar_tag_box clear"><em>'+rk.i18n('DASH___387')+'：</em><em style="margin-right: 10px;">'+rk.i18n('DASH___392')+'</em>',
                '<select class="js-date_value">',
                o.dataDisplay == '1' ? '<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option>' : '<option value="1">1</option><option value="2">2</option>',
                '</select>',
                '<select class="js-date_type"><option value="1" ', o.dataDisplay == '1' ? 'selected' : '', '>'+rk.i18n('CRM_CORE_WEEK')+'</option><option value="2"', o.dataDisplay == '2' ? 'selected' : '', '>'+rk.i18n('CRM_CORE_MONTH')+'</option></select>',
                '</div>',
                '<a title="" class="green_button" href="javascript:;" type="', chartType.salesRecentFocus, '">'+rk.i18n('CRM_CORE_CONFIRM')+'</a>',
                '</div>',
                '</div>'
            ].join('');
            var $date = ['<a period="month" class="month_tag js-chart-filter ', o.dataDisplay == '1' ? 'tabon' : '', '">'+rk.i18n('DASH___393')+'<em>|</em></a>',
                '<a period="quarter" class="season_tag js-chart-filter ', o.dataDisplay == '2' ? 'tabon' : '', '">'+rk.i18n('DASH___394')+'</a>',
                '<a period="year" class="season_tag js-chart-filter ', o.dataDisplay == '3' ? 'tabon' : '', '"><em style="margin-right: 10px">|</em>'+rk.i18n('DASH___395')+'</a>'
            ].join('');

            var $dateWeek = ['<a period="week" class="month_tag js-chart-filter ', o.dataDisplay == '1' ? 'tabon' : '', '">'+rk.i18n('DASH___396')+'<em>|</em></a>',
                '<a period="month" class="season_tag js-chart-filter ', o.dataDisplay == '2' ? 'tabon' : '', '">'+rk.i18n('DASH___393')+'</a>',
                '<a period="quarter" class="season_tag js-chart-filter ', o.dataDisplay == '3' ? 'tabon' : '', '"><em style="margin-right: 10px">|</em>'+rk.i18n('DASH___394')+'</a>'
            ].join('');
            $result = [o.type == chartType.salesFunnel ? $calendarInfo : '',
                o.type == chartType.salesFunnel || o.type == chartType.salesGoal || o.type == chartType.salesPK || o.type == chartType.top10Customer || o.type == chartType.top10Opportunity ? $date : '',
                o.type == chartType.salesActivity ? $dateWeek : '',
                o.type == chartType.salesRecentFocus ? $rescentFocusInfo + '<span class="month_tag">'+rk.i18n('DASH___392')+' <span class="js-recent_num">1</span> <span class="js-recent_type">' + (o.dataDisplay == '1' ? rk.i18n('CRM_CORE_WEEK') : rk.i18n('CRM_CORE_MONTH')) + '</span></span>' : ''
            ].join('');
            return $result;
        }
    });
});